package com.garlic.face.jlf.ui;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.garlic.face.jlf.R;
import com.garlic.face.jlf.base.BaseActivity;
import com.garlic.face.jlf.transaction.Means;
import com.garlic.face.jlf.transaction.ServiceInterface;
import com.garlic.face.jlf.transaction.constances.CommonConstant;
import com.garlic.face.jlf.transaction.constances.JLFConstant;
import com.garlic.face.jlf.utils.LogUtils;
import com.garlic.face.jlf.utils.PrintUtil;
import com.garlic.face.jlf.utils.ToastUtils;
import com.garlic.face.jlf.utils.Tools;
import com.printer.sdk.PrinterConstants;
import com.printsdk.usbsdk.UsbDriver;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by shiyanqi on 18/9/15.
 */

public class PrintAuthorizationCodeActivity extends BaseActivity {
	private static final String TAG = "PrintAuthorizationCodeActivity";
	private EditText supervisor;
	private EditText supervisorPwd;
	private InputMethodManager inputMethodManager; // 软键盘
	private static UsbDriver mUsbDriver;
	private static UsbDevice mUSBDevice;
	private ArrayList<UsbDevice> deviceList;
	private MyHandler myHandler = new MyHandler(this);
	public static final String ACTION_USB_PERMISSION = "com.android.usb.USB_PERMISSION";

	private static class MyHandler extends Handler {
		private WeakReference<PrintAuthorizationCodeActivity> mLogActivityWeak;

		public MyHandler(PrintAuthorizationCodeActivity printAuthorizationCodeActivity) {
			mLogActivityWeak = new WeakReference<>(printAuthorizationCodeActivity);
		}

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
				case PrinterConstants.Connect.SUCCESS:
					String connectOk = "USE打印机-连接成功";
					LogUtils.d(connectOk, true);
//                    PrintUtil.printLog(getmUSBDevice(), getmUsbDriver());
//					PrintUtil.printjlf(getmUSBDevice(), getmUsbDriver());
					break;
				case PrinterConstants.Connect.FAILED:
					String connectFaile = "USB打印机-连接失败";
					ToastUtils.toastShow(connectFaile, ToastUtils.ERROR);
					LogUtils.e(connectFaile);
					break;
				case PrinterConstants.Connect.CLOSED:
					String connectClose = "USB打印机-连接关闭";
					ToastUtils.toastShow(connectClose, ToastUtils.INFO);
					LogUtils.e(connectClose);
					break;
				case PrinterConstants.Connect.NODEVICE:
					String connectNo = "USB打印机-没有连接";
					ToastUtils.toastShow(connectNo, ToastUtils.ERROR);
					LogUtils.e(connectNo);
					break;
				case CommonConstant.NET_STATE_UNCONNECT:
					String netStateUnconnect = "网络错误";
					ToastUtils.toastShow(netStateUnconnect, ToastUtils.ERROR);
					LogUtils.e(netStateUnconnect);
					break;
				default:
					break;
			}
		}
	}
	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_print_authorization_code);

		supervisor = findViewById(R.id.supervisor);
		supervisorPwd = findViewById(R.id.supervisor_pwd);
		supervisor.setInputType(InputType.TYPE_CLASS_NUMBER);
		inputMethodManager = ((InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE));

		findViewById(R.id.print_button).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				if(informationIsOk(supervisor.getText().toString().trim(), supervisorPwd.getText().toString().trim())){
					//验证管理员账号密码
					showProgress();
					ServiceInterface.getInstance().superVisor(supervisor.getText().toString().trim(), supervisorPwd.getText().toString().trim(), JLFConstant.SCO_PRINT_SIBARCODE);
//					printAuthCode(supervisor.getText().toString().trim(), supervisorPwd.getText().toString().trim());
				}
			}
		});
		findViewById(R.id.print_close).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				finish();
			}
		});
		EventBus.getDefault().register(this);
		init();
	}

	private void init() {
		UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
		usbAutoConn(manager);
	}

	/**
	 * 打开自动连接打印机
	 *
	 * @param manager
	 */
	public void usbAutoConn(UsbManager manager) {
		doDiscovery(manager);
		if (deviceList.isEmpty()) {
			ToastUtils.toastShow("USB打印机没有连接", ToastUtils.ERROR);
			return;
		}
		mUSBDevice = deviceList.get(0);
		if (mUSBDevice == null) {
			String connectFaile = "USE打印机-连接失败";
			LogUtils.e(TAG + connectFaile);
			ToastUtils.toastShow(connectFaile, ToastUtils.ERROR);
			return;
		}
		// 美松
		mUsbDriver = new UsbDriver(manager, this);
		LogUtils.e("deviceName: " + mUSBDevice.getDeviceName());
		UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
		try {
			if (mUsbManager != null) {
				if (mUsbManager.hasPermission(mUSBDevice)) {
					openUsbConnect();
				} else {
					// 没有权限询问用户是否授予权限
					PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
					IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
					filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
					filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
					registerReceiver(mUsbReceiver, filter);
					mUsbManager.requestPermission(mUSBDevice, pendingIntent); // 该代码执行后，系统弹出一个对话框
				}
			} else {
				String msg = "USBManager空指针";
				LogUtils.e(TAG + msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			String msg = "USB-Service空指针";
			LogUtils.e(msg);
		}
	}

	private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (ACTION_USB_PERMISSION.equals(action)) {
				synchronized (this) {
					unregisterReceiver(mUsbReceiver);
					UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
					if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
							&& mUSBDevice.equals(device)) {
						openUsbConnect();
					} else {
						myHandler.obtainMessage(PrinterConstants.Connect.FAILED).sendToTarget();
					}
				}
			}
		}
	};


	/**
	 * 打开USB打印机
	 */
	private void openUsbConnect() {
		mUsbDriver.usbAttached(mUSBDevice);
		boolean b = mUsbDriver.openUsbDevice(mUSBDevice);
		if(b){
			myHandler.obtainMessage(PrinterConstants.Connect.SUCCESS).sendToTarget();
		}
	}

	/**
	 * 没有则自动获取设备
	 *
	 * @param manager
	 */
	private void doDiscovery(UsbManager manager) {
		HashMap<String, UsbDevice> devices = manager.getDeviceList();
		deviceList = new ArrayList<UsbDevice>();
		for (UsbDevice device : devices.values()) {
			if (PrintUtil.isUsbPrinter(device)) {
				LogUtils.d("doDiscovery: " + device.getDeviceName(), true);
				deviceList.add(device);
			}
//            if (USBPort.isUsbPrinter(device)) {
//                deviceList.add(device);
//            }
		}
	}


	/**
	 * 隐藏软键盘
	 */
	private void hideSoftInput(){
		if (inputMethodManager != null) {
			// 参数1：当前viewTree任意一个view的windowToken     参数2：没要求0即可
			inputMethodManager.hideSoftInputFromWindow(supervisor.getWindowToken(), 0);
		}
	}

	/**
	 * 判断是否为空
	 *
	 * @return
	 */
	private boolean informationIsOk(String authCode, String authCodePwd) {
		boolean ret = true;
		StringBuffer sb = new StringBuffer("");
		if (authCode.length() <= 0) {
			ret = false;
			sb.append("管理员账号不能为空 ");
		}
		if (authCodePwd.length() <= 0) {
			ret = false;
			sb.append("管理员密码不能为空 ");
		}
		if (!ret) {
			ToastUtils.toastShow(sb.toString().trim(), ToastUtils.ERROR);
		}
		return ret;
	}

	/**
	 * 打印权限码
	 */
	private void printAuthCode(String supervisor, String supervisorPwd){
		PrintUtil.printAuthCode(PrintAuthorizationCodeActivity.getmUSBDevice(), PrintAuthorizationCodeActivity.getmUsbDriver(), supervisor, supervisorPwd);
	}

	public static UsbDevice getmUSBDevice() {
		return mUSBDevice;
	}
	public static UsbDriver getmUsbDriver() {
		return mUsbDriver;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(mUsbDriver != null){
			mUsbDriver.closeUsbDevice(mUSBDevice);
		}
		EventBus.getDefault().unregister(this);
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onReceiveResponse(JSONObject jsonObject) {
		parseJson(jsonObject);
	}

	private void parseJson(JSONObject jsonObject) {
		hideProgress();
		String interfacetype = "";
		String retflag = "";
		String retmsg = "";
		try {
			interfacetype = jsonObject.getString("INTERFACETYPE");
			retflag = jsonObject.getString("retflag");
			retmsg = jsonObject.getString("retmsg");
			if (interfacetype.equals(JLFConstant.TAG_SUPERVISOR_RESPONSE)) {
				retflag = jsonObject.getString("retflag");
				retmsg = jsonObject.getString("retmsg");
				//TODO 刷卡输完管理员账号密码返回可能retflag为1，return retmsg为100000
				if (retflag.equals("0")) {
					Log.e("-------print ", "0");
					printAuthCode(supervisor.getText().toString().trim(), supervisorPwd.getText().toString().trim());
				} else {
					ToastUtils.toastShow(retmsg, ToastUtils.ERROR);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}


}
